<?php
class model_members extends base_model{
	private $result = array(
		'state' => 404,
		'message' => '',
	);
	
	public function __construct() {
		parent::__construct();
	}
	# region 游戏列表
	public function mod_games_items()
    {
        $redisKey = $this->redisPrefix['MANAGE'] . 'games_list';
        $result = $this->redisGet($redisKey);
        if(!$result) {
            $sql = "SELECT `id`,`title` FROM `@@games` ORDER BY `sort` ASC";
            $data = $this->db->query($sql,3);
            $result = array();
            foreach ($data as $k=>$v)
            {
                $result[$v['id']] = $v['title'];
            }
            $this->redisSet($redisKey, $result);
        }
        return $result;
    }
    # endregion

	# region 用户等级管理
	//拉取用户等级数据
	public function mod_members_leves_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            $where_txt .= " AND `title` LIKE '%".$args['sKey']."%'";
        }

        $sql = "SELECT ~field~ FROM `@@userlevel` WHERE 1 {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => '*',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => 'ORDER BY `lid` ASC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
	}
    # endregion

    # region 代理等级管理
    //拉取数据
    public function mod_agent_level_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            $where_txt .= " AND `title` LIKE '%".$args['sKey']."%'";
        }

        $sql = "SELECT ~field~ FROM `@@agentlevel` WHERE 1 {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => '*',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => 'ORDER BY `lid` ASC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 用户数据
    public function mod_members_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            $where_txt .= " AND (u.`uno` LIKE '%".$args['sKey']."%' OR u.`nickname` LIKE '%".$args['sKey']."%') OR `tel`='".$args['sKey']."'";
        }else{
            if(!empty($args['puid'])){
                if(intval($args['t'])==1){
                    $where_txt .= " AND u.`parentid` = " . $args['puid'];
                }else {
                    $where_txt .= " AND FIND_IN_SET('" . $args['puid'] . "',u.`parents`)";
                }
            }else {
                $fromTime = strtotime($args['fromTime']);
                $toTime = strtotime($args['toTime']) + 86400;
                $where_txt .= " AND u.`regtimes` BETWEEN " . $fromTime . " AND " . $toTime . "";
            }
        }

        if($args['usertype']!='') $where_txt .= ' AND u.`usertype`='.intval($args['usertype']);
        if($args['userlevel']!='') $where_txt .= ' AND u.`userlevel`='.intval($args['userlevel']);
        if($args['agentlevel']!='') $where_txt .= ' AND u.`agentlevel`='.intval($args['agentlevel']);
        if($args['regip']!='') $where_txt .= ' AND u.`regip`='.intval(ip2long($args['regip']));

        $sql = "SELECT ~field~ FROM `@@users` u WHERE 1 {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'u.uid,u.uno,u.nickname,u.regtimes,u.lastip,u.coin,u.score,u.isdelete,u.agentlevel,u.usertype,u.betcoin,u.regip,(SELECT IFNULL(SUM(r.`amount`),0) from `@@users_recharge` r where r.state=1 AND r.uid=u.uid) AS rechargecoin,(SELECT IFNULL(SUM(c.`amount`),0) from `@@users_cash` c where c.state=1 AND c.uid=u.uid) AS cashcoin',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY u.`regtimes` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);

        $total_fields = "u.usertype,COUNT(u.uid) AS _TOTAL";
        $sql = "SELECT {$total_fields} FROM `@@users` u WHERE 1 {$where_txt} GROUP BY u.usertype";
        $total = $this->db->query($sql, 3);

        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
            'total' => $total,
        );
    }
    # endregion

    # region 代理用户
    public function mod_agentuser_list($args){
        $where_txt = "u.`usertype`= 2";
        if(!empty($args['sKey'])){
            $where_txt .= " AND (u.`uno` ='".$args['sKey']."' OR `tel`='".$args['sKey']."')";
        }else{
            $fromTime = strtotime($args['fromTime']);
            $toTime = strtotime($args['toTime']) + 86400;

            $where_txt .= " AND u.`regtimes` BETWEEN ".$fromTime." AND ".$toTime."";
        }
        $orderby = ' ORDER BY u.`regtimes` DESC';
        if(!empty($args['sortfield'])){
            $orderby = ' ORDER BY '.$args['sortfield'].' '.$args['sorttype'];
        }

        $sql = "SELECT ~field~ FROM `@@users` u WHERE {$where_txt} ~order~ ~limit~";
        # 佣金 Commission
        $fields = ',u.`backtotal` AS commission';
        # 本代理的提现
        $fields .= ",(SELECT IFNULL(SUM(cuc.amount),0) FROM `@@users_cash` cuc WHERE cuc.`state`=1 AND cuc.`uid`=u.`uid`) AS cash";
        # 直属用户
        $fields .= ',(SELECT COUNT(1) FROM `@@users` du WHERE du.`parentid`=u.`uid`) AS directlys';
        # 团队用户
        $fields .= ",(SELECT COUNT(1) FROM `@@users` dt WHERE FIND_IN_SET(u.`uid`,dt.`parents`)) AS teams";
        # 直属盈亏
        $fields .= ",(SELECT IFNULL(SUM(du2.profit),0) FROM `@@users` du2 WHERE du2.`parentid` = u.`uid` ) AS directlysprofit";
        # 直属充值
        $fields .= ",(SELECT IFNULL(SUM(du3.recharge),0) FROM `@@users` du3 WHERE du3.`parentid` = u.`uid` ) AS directlysrecharge";
        # 直属提现
        $fields .= ",(SELECT IFNULL(SUM(uc.amount),0) FROM `@@users_cash` uc WHERE uc.`state`=1 AND  FIND_IN_SET(uc.`uid`, (SELECT GROUP_CONCAT(ucu.uid) FROM `@@users` ucu WHERE ucu.`parentid`=u.`uid`))) AS directlyscash";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'u.uid,u.uno,u.nickname,u.regtimes,u.coin,u.isdelete,u.agentlevel,u.backtotal,u.recharge,u.rebate'.$fields,
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => $orderby,
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    public function mod_members_userLevel_forSelect(){
        $redisKey = $this->redisPrefix['MANAGE'] . 'userlevel_select';
	    $_result = $this->redisGet($redisKey);
	    if(!$_result) {
            $sql = "SELECT `lid`,`title` FROM `@@userlevel` ORDER BY `lid` ASC";
            $data = $this->db->query($sql, 3);
            $_result = array();
            foreach ($data as $k => $v) {
                $_result[$v['lid']] = $v['title'];
            }
            $this->redisSet($redisKey, $_result);
        }
        return $_result;
    }
    public function mod_members_agentLevel_forSelect(){
        $redisKey = $this->redisPrefix['MANAGE'] . 'agentlevel_select';
        $_result = $this->redisGet($redisKey);
        if(!$_result) {
            $sql = "SELECT `lid`,`title` FROM `@@agentlevel` ORDER BY `lid` ASC";
            $data = $this->db->query($sql, 3);
            $_result = array();
            foreach ($data as $k => $v) {
                $_result[$v['lid']] = $v['title'];
            }
            $this->redisSet($redisKey, $_result);
        }
        return $_result;
    }
    # endregion

    # region 代理链接管理
    public function mod_agentlinks_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            $where_txt .= " AND u.`uno` ='".$args['sKey']."'";
        }else{
            $fromTime = strtotime($args['fromTime']);
            $toTime = strtotime($args['toTime']) + 86400;

            $where_txt .= " AND l.`actiontimes` BETWEEN ".$fromTime." AND ".$toTime."";
        }
        if(!empty($args['usertype'])){
            $where_txt .= " AND l.`usertype` =".$args['usertype'];
        }
        $orderby = ' ORDER BY l.`id` DESC';
        if(!empty($args['sortfield'])){
            $orderby = ' ORDER BY '.$args['sortfield'].' '.$args['sorttype'];
        }

        $sql = "SELECT ~field~ FROM `@@agentlinks` l,`@@users` u WHERE l.`uid`=u.`uid` {$where_txt} ~order~ ~limit~";
        $sql_arr = array(
            'field' => 'u.nickname,u.uno,l.uid,l.id,l.rebate,l.actiontimes,l.state,l.numbers,l.usertype',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => $orderby,
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 帐变日志
    public function mod_coinlog_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                // $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR l.`uid`=" . intval($args['sKey']) . " OR l.`ex2`='" . $args['sKey'] . "')";
                $where_txt .= " AND u.`uno`='" . $args['sKey'] . "'";
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND l.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }
        if(!empty($args['liqtype'])){
            $where_txt .= " AND l.`liqtype`=".$args['liqtype'];
        }

        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        $where_txt .= " AND l.`times` BETWEEN ".$fromTime." AND ".$toTime."";

        $db_ym = date('Ym');

        $sql = "SELECT ~field~ FROM `@@coinlog_".$db_ym."` l, `@@users` u WHERE u.`uid`=l.`uid` {$where_txt} ~order~ ~limit~";
        //echo $sql;
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'l.id,l.uid,l.coin,l.usercoin,l.usertype,l.ex1,l.ex2,l.ex3,l.times,l.gameid,l.liqtype,u.`uno`,u.`nickname`,(SELECT g.`title` FROM `@@games` g WHERE g.`id`=l.`gameid`) as gamename',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY l.`id` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 积分帐变日志
    public function mod_scorelog_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR l.`uid`=" . $args['sKey'] . " OR l.`gameid`=" . $args['sKey'] . " OR l.`ex2='" . $args['sKey'] . "'";
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND l.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }
        if(!empty($args['liqtype'])){
            $where_txt .= " AND l.`liqtype`=".$args['liqtype'];
        }

        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        $where_txt .= " AND l.`times` BETWEEN ".$fromTime." AND ".$toTime."";

        $sql = "SELECT ~field~ FROM `@@scorelog` l, `@@users` u WHERE u.`uid`=l.`uid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'l.*,u.`uno`,u.`nickname`,(SELECT g.`title` FROM `@@games` g WHERE g.`id`=l.`gameid`) as gamename',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY `id` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 赠送帐变日志
    public function mod_givecoinlog_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR l.`uid`=" . $args['sKey'] . " OR l.`gameid`=" . $args['sKey'] . " OR l.`ex2='" . $args['sKey'] . "'";
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND l.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }
        if(!empty($args['liqtype'])){
            $where_txt .= " AND l.`liqtype`=".$args['liqtype'];
        }

        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        $where_txt .= " AND l.`times` BETWEEN ".$fromTime." AND ".$toTime."";

        $sql = "SELECT ~field~ FROM `@@givecoinlog` l, `@@users` u WHERE u.`uid`=l.`uid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'l.*,u.`uno`,u.`nickname`,(SELECT g.`title` FROM `@@games` g WHERE g.`id`=l.`gameid`) as gamename',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY `id` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 转包记录
    public function mod_transferlog_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR l.`uid`=" . $args['sKey'];
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND l.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }

        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        $where_txt .= " AND l.`times` BETWEEN ".$fromTime." AND ".$toTime."";

        $sql = "SELECT ~field~ FROM `@@transfer_log` l, `@@users` u WHERE u.`uid`=l.`touid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'l.`id`,l.`touid`,l.`fromuid`,l.`coin`,l.`rate`,l.`times`,l.`state`,u.`uno` as touno,u.`nickname` as tonickname,(SELECT `uno` FROM `rp_users` WHERE l.`fromuid`=uid LIMIT 1) as fromuno,(SELECT `nickname` FROM `rp_users` WHERE l.`fromuid`=uid LIMIT 1) as fromnickname',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY `times` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 发包记录
    public function mod_betslog_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR l.`uid`=" . intval($args['sKey']) . ")";
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND l.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }
        if($args['state']!='') $where_txt .= ' AND l.`state`='.$args['state'];
        if($args['gameid']!='') $where_txt .= ' AND l.`gameid`='.$args['gameid'];

        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        $where_txt .= " AND l.`begintimes` BETWEEN ".$fromTime." AND ".$toTime."";

        $sql = "SELECT ~field~ FROM `@@bets` l LEFT JOIN `@@probability_log` rl ON rl.`issue`=l.`issue`, `@@users` u WHERE u.`uid`=l.`uid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'l.*,u.`uno`,(SELECT IFNULL(SUM(ls.ticket),0) FROM `@@betslog` ls WHERE ls.`issue`=l.issue) AS ticket,(SELECT IFNULL(SUM(ls.winerprofit),0) FROM `@@betslog` ls WHERE ls.`issue`=l.issue) AS winerprofit,rl.`psw`,rl.`play`,rl.`inside`,rl.`pret`,rl.`rint`,rl.`bankerwon`',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY `begintimes` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);

        $total_fields = 'IFNULL(SUM(l.coin),0) AS coin,IFNULL(SUM(l.ticket),0) AS ticket,IFNULL(SUM(l.winerprofit),0) AS winerprofit';
        $where_txt = str_replace('l.`begintimes`','l.`times`', $where_txt);
        $sql = "SELECT {$total_fields} FROM `@@betslog` l, `@@users` u WHERE  u.`uid`=l.`uid` {$where_txt}";
        $total = $this->totalFieldsCount($sql,$total_fields);

        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
            'total' => $total,
        );
    }
    # endregion

    # region 红包参与记录
    public function mod_betslogforuser_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR l.`uid`=" . intval($args['sKey']) . ")";
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND l.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }
        if($args['state']!='') $where_txt .= ' AND l.`state`='.$args['state'];
        if($args['gameid']!='') $where_txt .= ' AND l.`gameid`='.$args['gameid'];
        if($args['isusertype']=='0') $where_txt .= ' AND u.`usertype`>0 AND u.`usertype`<3';

        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        $where_txt .= " AND l.`times` BETWEEN ".$fromTime." AND ".$toTime."";

        $sql = "SELECT ~field~ FROM `@@betslog` l LEFT JOIN `@@probability_log` rl ON rl.`issue`=l.`issue`, `@@users` u WHERE u.`uid`=l.`uid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'l.*,u.`uno`,u.`nickname`,rl.`psw`,rl.`play`,rl.`inside`,rl.`pret`,rl.`rint`,rl.`bankerwon`',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY l.`times` DESC, l.`issue` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);

        //$total_fields = 'IFNULL(SUM(l.betcoin),0) AS betcoin,IFNULL(SUM(l.coin),0) AS coin,IFNULL(SUM(l.ticket),0) AS ticket,IFNULL(SUM(l.winerprofit),0) AS winerprofit,IFNULL(SUM(l.profit),0) AS profit';
        //$where_txt = str_replace('l.`begintimes`','l.`times`', $where_txt);
        //$sql = "SELECT {$total_fields} FROM `@@betslog` l, `@@users` u WHERE  u.`uid`=l.`uid` {$where_txt}";
        //$total = $this->totalFieldsCount($sql,$total_fields);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
            //'total' => $total,
        );
    }
    # endregion

    # region 抢包明细
    public function mod_grablog_list($issue){
        if(empty($issue)){
            core::error('红包期号错误');
        }

        $redis_key = $this->redisPrefix['GOISSUE'].$issue;
        if($this->redis->exists($redis_key))
        {
            $data = $this->redisGet($redis_key);
        }else {
            $sql = "SELECT b.`id`,b.`uid`,b.`issue`,b.`gameid`,(SELECT o.`cardtitle` FROM `@@games_odds` o WHERE o.cardtype=b.`cardtype` AND b.`odds`=o.`odds` AND o.`gameid`=b.`gameid` LIMIT 1) AS cardtitle,b.`odds`,b.`mantissa`,b.`coin`,b.`times`,b.`ticket`,b.`winerprofit`,b.`profit`,u.`uid` AS userid,u.`nickname`,u.`avatar`,u.`uno` ";
            $sql .="FROM `@@betslog` b,`@@users` u WHERE u.`uid`=b.`uid` AND b.`issue`='{$issue}' ORDER BY b.`times` ASC";
            $betlogs = $this->db->query($sql,3);

            $autosql = "SELECT b.`id`,b.`uid`,b.`issue`,b.`gameid`,(SELECT o.`cardtitle` FROM `@@games_odds` o WHERE o.cardtype=b.`cardtype` AND b.`odds`=o.`odds` AND o.`gameid`=b.`gameid` LIMIT 1) AS cardtitle,b.`odds`,b.`mantissa`,b.`coin`,b.`times`,b.`ticket`,b.`winerprofit`,b.`profit`,u.`uid` AS userid,u.`nickname`,u.`avatar`,u.`uno` ";
            $autosql .="FROM `@@autobetslog` b,`@@users` u WHERE u.`uid`=b.`uid` AND b.`issue`='{$issue}' ORDER BY b.`times` ASC";

            $autobetlogs = $this->db->query($autosql,3);

            $data['grabusers'] = array_merge($betlogs,$autobetlogs);

            $sql = "SELECT * FROM `@@bets` WHERE `issue`='{$issue}'";
            //print_r($sql);
            $data['datas'] = $this->db->query($sql,2);
            $this->redisSetEx($redis_key, $data, 300);
        }

        return array(
            'datas' => $data,
            'record' => count($data),
        );
    }
    # endregion

    # region 用户银行卡管理
    public function mod_banklist_for_selectoption()
    {
        $redisKey = $this->redisPrefix['MANAGE'] . 'bank_list';
        $result = $this->redisGet($redisKey);
        if(!$result) {
            $sql = "SELECT `id`,`title` FROM `@@bank_list` ORDER BY `sort` ASC";
            $data = $this->db->query($sql,3);
            $result = array();
            foreach ($data as $k=>$v)
            {
                $result[$v['id']] = $v['title'];
            }
            $this->redisSet($redisKey, $result);
        }
        return $result;
    }
    public function mod_userbanks_list($args)
    {
        $where_txt = " AND b.`isdelete`=0";
        if(!empty($args['sKey'])){
            $args['sKey'] = str_replace(' ', '', $args['sKey']);
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR b.`uid`=" . intval($args['sKey'])." OR b.`account` LIKE '%".$args['sKey']."%' OR b.`name` LIKE '%".$args['sKey']."%')";
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND b.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }
        if(!empty($args['bankid'])){
            $where_txt .= " AND b.`bankid`=".intval($args['bankid']);
        }

        $where_txt .= "";

        $sql = "SELECT ~field~ FROM `@@users_bank` b, `@@users` u, `@@bank_list` bn WHERE u.`uid`=b.`uid` AND bn.`id`=b.`bankid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'b.*,u.`uid`,u.`uno`,u.`nickname`,bn.`title`',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY b.`id` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 玩家充值处理
    public function mod_payway_list()
    {
        $sql = "SELECT `id`,`info` FROM `@@pay_way` ORDER BY `sort` ASC";
        $datas = $this->db->query($sql,3);
        $result = array();
        foreach($datas as $k=>$v)
        {
            $result[$v['id']] = $v['info'];
        }
        return $result;
    }
    public function mod_rechargelog_item($id)
    {
        $sql = "SELECT l.*,u.parentid,u.userlevel FROM `@@users_recharge` l,`@@users` u WHERE l.`id`=".$id." AND u.uid=l.uid LIMIT 1";
        return $this->db->query($sql,2);
    }
    public function mod_rechargelog_list($args)
    {
        $where_txt = "";
        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR b.`uid`=" . intval($args['sKey']) .")";
            }else{
                switch (strtolower($args['field'])){
                    case 'rechargeid':
                        $where_txt .= " AND b.`rechargeid`='".$args['sKey']."'";
                        break;
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND b.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
            $where_txt .= " AND b.`actiontime` BETWEEN ".$fromTime." AND ".$toTime."";
        }else{
            $where_txt .= " AND b.usertype IN(1,2,3) AND b.`actiontime` BETWEEN ".$fromTime." AND ".$toTime."";
        }
        if(!empty($args['paywayid'])){
            $where_txt .= " AND b.`paywayid`=".intval($args['paywayid']);
        }
        if(!empty($args['lineid'])){
            $where_txt .= " AND b.`lineid`=".intval($args['lineid']);
        }
        if($args['state']!=''){
            $where_txt .= " AND b.`state`=".intval($args['state']);
        }

        $sql = "SELECT ~field~ FROM `@@users_recharge` b, `@@users` u, `@@rechargeline` r,`@@pay_way` p WHERE u.`uid`=b.`uid` AND r.`id`=b.`lineid` AND p.`id`=b.`paywayid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'b.*,u.`uno`,u.`nickname`,r.`username` AS uname,r.`account`,p.`info` AS paywayinfo',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY b.`id` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);

        $total_fields = "IFNULL(SUM(b.amount),0) AS amount,IFNULL(SUM(b.rechargeamount),0) AS rechargeamount";
        $sql = "SELECT {$total_fields} FROM `@@users_recharge` b, `@@users` u, `@@rechargeline` r WHERE u.`uid`=b.`uid` AND r.`id`=b.`lineid` {$where_txt}";
        $total = $this->totalFieldsCount($sql,$total_fields);

        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
            'total' => $total,
        );
    }
    # 通过充值订单来查找充值线路的赠送
    public function mod_rechargelog_item_give($id)
    {
        $sql = "SELECT l.`give` AS coin FROM `@@users_recharge` r,`@@rechargeline` l WHERE r.`id`=".$id." AND r.`lineid`=l.`id` LIMIT 1";
        return $this->db->query($sql,2);
    }
    # endregion

    # region 提现处理
    public function mod_users_cash_faild_info()
    {
        $sql = "SELECT `title` FROM `@@users_cash_faild_info`";
        return $this->db->query($sql,3);
    }
    public function mod_cashlog_list($args)
    {
        $where_txt = "";
        if(!empty($args['sKey'])){
            if(empty($args['field'])) {
                $where_txt .= " AND (u.`uno`='" . $args['sKey'] . "' OR b.`uid`=" . intval($args['sKey']) .')';
            }else{
                switch (strtolower($args['field'])){
                    case 'uno':
                        $where_txt .= " AND u.`".$args['field']."`='".$args['sKey']."'";
                        break;
                    default:
                        $where_txt .= " AND b.`".$args['field']."`='".$args['sKey']."'";
                        break;
                }
            }
        }
        if(!empty($args['bankid'])){
            $where_txt .= " AND bn.`bankid`=".intval($args['bankid']);
        }
        if($args['state']!=''){
            $where_txt .= " AND b.`state`=".intval($args['state']);
        }

        $fromTime = strtotime($args['fromTime']);
        $toTime = strtotime($args['toTime']) + 86400;

        $where_txt .= " AND b.`cashtime` BETWEEN ".$fromTime." AND ".$toTime."";

        $sql = "SELECT ~field~ FROM `@@users_cash` b, `@@users` u, `@@users_bank` bn WHERE u.`uid`=b.`uid` AND b.`usertype`<>0 AND u.`usertype`<>0 AND bn.`id`=b.`bankid` {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'b.*,u.`uid`,u.`uno`,u.`nickname`,bn.`bankid` AS bid,bn.`name`,bn.`account`,bn.`openadds`',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY b.`id` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);

        $total_fields = "IFNULL(SUM(amount),0) AS amount";
        $sql = "SELECT {$total_fields} FROM `@@users_cash` b, `@@users` u, `@@users_bank` bn WHERE u.`uid`=b.`uid` AND b.`usertype`<>3 AND u.`usertype`<>3 AND bn.`id`=b.`bankid` {$where_txt}";
        $total = $this->totalFieldsCount($sql,$total_fields);

        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
            'total' => $total,
        );
    }
    # endregion

    # region 自动发包抱包用户数据
    public function mod_autosend_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            $where_txt .= " AND (u.`uno` LIKE '%".$args['sKey']."%' OR u.`nickname` LIKE '%".$args['sKey']."%')";
        }
        if(!empty($args['gameid'])){
            $where_txt .= " AND s.`gameid`=".$args['gameid'];
        }

        $sql = "SELECT ~field~ FROM `@@autosend` s, `@@users` u WHERE u.uid=s.uid {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'u.uid,u.uno,u.nickname,u.regtimes,u.coin,u.isdelete,u.usertype,u.betcoin,u.regip,s.gameid',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY s.uid DESC,s.`gameid` DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 自助发包
    public function mod_autosend_togame($gameid)
    {
        $paras['cmd'] = 'sendred';
        $paras['needusernum'] = 5;
        $paras['remoteip'] = '2130706433';
        $paras['nowtime'] = time();
        $paras['ws'] = 0; // 尾数
        $paras['coin'] = 0;
        if($gameid==3)
        {
            $paras['ws'] = mt_rand(0,9);
        }


        $game['game'] = $this->getRow('@@games','*',array('id'=>$gameid));
        $game['odds'] = $this->db->query('SELECT * FROM `@@games_odds` WHERE `gameid`='.$gameid, 3);


        //红包的投注金额
        $testMinCoin = explode(',', $game['game']['betscoinlist']);
        $paras['coin'] = intval($testMinCoin[0]);
        $betCoin = $paras['coin'];
        # 红包的金额
        $redcoin = $betCoin;
        //检测包的数量是否正确
        $testNeedUser = explode(',', $game['game']['manymen']);
        # 最小包数发送
        $paras['needusernum'] = $testNeedUser[0];

        if(!in_array($paras['needusernum'], $testNeedUser))
        {
            core::error('包数不正确');
        }
        //本次发包所需要金币数量(有庄：游戏的人数-1 * $betCoin，无庄：$betCoin)
        //默认为无庄模式
        $betNeedCoin = $betCoin;

        $autoSendUids = $this->db->query('SELECT GROUP_CONCAT(uid) AS uids FROM @@autosend WHERE gameid='.$gameid,2);
        $autoSendUids = $autoSendUids['uids'];


        if($game['game']['ishavebanker'])
        {
            //庄家的预计赔注（(人数 -1) * 红包的基本投注 * 最大赔率)）
            //找出游戏的最大赔率( 游戏的赔率是按从大到小的来排序，所以最上面一个就是最大的赔率，后台设置时需要把牌型最大的winsort值最为最大)
            $maxodds = $game['odds'][0]['odds'];

            # 如果有庄但没有固定发包金额的
            $betNeedCoinRed = $game['game']['establishcoin'] > 0 ? $game['game']['establishcoin'] : $betCoin;
            //-----
            $betNeedCoin = (($paras['needusernum'] - 1) * $betCoin * $maxodds);

            $users = $this->db->query('SELECT uid,uno,nickname,username,coin AS usercoin,avatar,usertype FROM `@@users` WHERE `uid` IN('.$autoSendUids.') AND `coin`>='.($betNeedCoin + $betNeedCoinRed),3);
            $user = array_rand($users, 1);
            $user = $users[$user];


            //如果金币余额不足退出发包并提示玩家(创建房间的费用+预计全赔的金额)
            if($user['usercoin'] < ($betNeedCoin + $betNeedCoinRed))
            {
                core::error('余额不足'.$user['usercoin'].' < ' . ($betNeedCoin + $betNeedCoinRed));//10005; //金币不足
            }
        }else{
            $users = $this->db->query('SELECT uid,uno,nickname,username,coin AS usercoin,avatar,usertype FROM `@@users` WHERE `uid` IN('.$autoSendUids.') AND `coin`>='.($betCoin),3);
            $user = array_rand($users, 1);
            $user = $users[$user];

            //如果金币余额不足退出发包并提示玩家(创建房间的费用+预计全赔的金额)
            if($user['usercoin'] < ($betCoin))
            {
                core::error('余额不足'.$user['usercoin'].' < ' . $betCoin);
            }
        }
        //如果发送或投注的的金额小于或大于游戏参数设置的值，退出并提示玩家
        if($betCoin < $game['game']['minbetcoin'] || $betCoin > $game['game']['maxbetcoin'])
        {
            core::error('设置的金额不正确('.$game['game']['minbetcoin'].'-'.$game['game']['maxbetcoin'].')');
        }
        #region 开始发包记录
        // 产生期号

        $currentIssue = $this->getIssue($gameid);


        # 红包的金额
        if(floatval($game['game']['establishcoin']) > 0)
        {
            $redcoin = floatval($game['game']['establishcoin']);
        }
        //记录发包的记录
        $send_log = array(
            'issue' => $currentIssue,
            'uid' => $user['uid'],
            'nickname' => $user['nickname'],
            'cur' => 1, //一发红包默认就是有自己一个人参与进去
            'coin' => $betCoin, //这里是发包的金币数量，每个人，不是加倍后的 ,红包的投注金额
            'redcoin' => $redcoin, // 红包的金额
            'ip' => $paras['remoteip'],
            'begintimes' => $paras['nowtime'],
            'mantissa' => $paras['ws'],
            'overtime' => $game['game']['overtime'],
            'gameid' => $game['game']['id'],
            'need' => $paras['needusernum'],
            'usertype' => $user['usertype'],
        );

        $currentRedEnvelopesID = $this->db->insert('@@bets', $send_log);
        //发包金额，两种模式：有庄和无庄，
        //有庄的需要发一个固定金币的红包
        $this->db->transaction('begin');
        if(floatval($game['game']['establishcoin']) > 0)
        {
            //记录固定发包的帐变
            $this->set_coin(
                array(
                    'uid' => $user['uid'],
                    'coin' => (0 - floatval($game['game']['establishcoin'])),
                    'gameid' => $game['game']['id'],
                    'liqtype' => 1, //发包扣款
                    'ex1' => $currentRedEnvelopesID,
                    'ex2' => $currentIssue,
                )
            );
        }else{
            # 如果没有固定发包的金额就要扣除，所发红包的金额
            if($game['game']['ishavebanker']==1) {
                $this->set_coin(
                    array(
                        'uid' => $user['uid'],
                        'coin' => (0 - floatval($betCoin)),
                        'gameid' => $game['game']['id'],
                        'liqtype' => 1, //发包扣款
                        'ex1' => $currentRedEnvelopesID,
                        'ex2' => $currentIssue,
                    )
                );
            }
        }
        //创建房间所需要扣的金币帐变
        $this->set_coin(
            array(
                'uid' => $user['uid'],
                'coin' => (0 - floatval($betNeedCoin)),
                'gameid' => $game['game']['id'],
                'liqtype' => 15, //创建房间
                'ex1' => $currentRedEnvelopesID,
                'ex2' => $currentIssue,
            )
        );
        //把自己加入到参与抢红包的队列数据中
        $betslog = array(
            'uid' => $user['uid'],
            'issue' => $currentIssue,
            'gameid' => $game['game']['id'],
            'times' => $paras['nowtime'],
            'betcoin' => $send_log['coin'],
        );
        $this->db->insert('@@betslog', $betslog);
        $this->db->transaction('commit');
        #endregion 结束发包动作

        //组织要推送给玩家的数据
        $result['state'] = 200;
        $result['gameid'] = $game['game']['id'];
        $result['groupname'] = 'game_'.$game['game']['id'];
        $result['user'] = $user;
        unset($result['msgid']);
        $result['datas'] = array(
            'id'=> $currentRedEnvelopesID,
            'issue'=> $currentIssue,
            'nickname'=> $user['nickname'],
            'avatar' => $user['avatar'],
            'need' => $paras['needusernum'], //所需要的人数为前台提交的人数，但需在前面进行验证安全性
            'times' => $this->formatTimes($paras['nowtime']),
            'overtime' => $game['game']['overtime'], //发包时的超时时间即为默认的超时数值
            'cur'=>1,
            'coin'=>$betCoin,
            'mantissa' => (intval($game['game']['id'])==3 ? $paras['ws'] : ''),
            'usertype' => $user['usertype'],
            'ispass' => 0,
        );

        //创建新的Redis队列，以红包的期数为Group的ID
        //在Redis队列后面加入新的玩家号码，如果不存在即创建一个新的
        $this->redis->rpush('games_doing_'.$currentIssue, $user['uno']);
        return $result;
    }
    # endregion

    # region 概率用户管理
    public function mod_probability_list($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            $where_txt .= " AND (u.`uno` = '".$args['sKey']."' OR u.`uid` = ".intval($args['sKey']).")";
        }

        if(!empty($args['fromTime'])) {
            $fromTime = strtotime($args['fromTime']);
            $toTime = strtotime($args['toTime']) + 86400;
            $where_txt .= " AND p.`jointime` BETWEEN " . $fromTime . " AND " . $toTime . "";
        }
        if($args['usertype'] != ''){
            $where_txt = ' AND u.`usertype`='.$args['usertype'];
        }

        $order = ' ORDER BY p.`jointime` DESC';
        if(!empty($args['sortfield'])){
            $order = ' ORDER BY '.$args['sortfield'].' '.$args['sorttype'];
        }


        $sql = "SELECT ~field~ FROM `@@users_probability` p, `@@users` u WHERE u.uid=p.uid {$where_txt} ~order~ ~limit~";

        //取出当前页的数据
        $sql_arr = array(
            'field' => 'p.winpoints,p.jointime,p.effectivetime,u.uid,u.uno,u.nickname,u.regtimes,u.coin,u.score,u.isdelete,u.usertype,u.betcoin,u.regip,u.recharge AS rechargecoin,(SELECT IFNULL(SUM(c.`amount`),0) from `@@users_cash` c where c.state=1 AND c.uid=u.uid) AS cashcoin,(SELECT IFNULL(SUM(bl.`profit`),0) AS _profit FROM `@@betslog` bl WHERE bl.`state`=1 AND bl.`uid`=u.`uid`) AS profit',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => $order,
        );

        $datas = $this->getTableRows($sql,$sql_arr);

        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion

    # region 会员登录日志
    public function mod_loginlog($args){
        $where_txt = "";
        if(!empty($args['sKey'])){
            $where_txt .= " AND `uno`='{$args['sKey']}'";
        }
        $sql = "SELECT ~field~ FROM `@@users_session` l,`@@users` u WHERE u.uid=l.uid {$where_txt} ~order~ ~limit~";
        //取出当前页的数据
        $sql_arr = array(
            'field' => 'u.uno,u.nickname,l.*',
            'page_current' => $args['page_current'],
            'pagesize' => $args['ps'],
            'order' => ' ORDER BY accesstime DESC',
        );
        $datas = $this->getTableRows($sql,$sql_arr);
        return array(
            'datas' => $datas['datas'],
            'record' => $datas['total'],
        );
    }
    # endregion
}